<?php
/**
 * 小程序用户认证API
 * 处理微信登录、用户信息管理等
 */

require_once 'base.php';

class AuthAPI extends MiniappBase {
    
    /**
     * 微信登录
     */
    public function login() {
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (empty($input['code'])) {
            $this->error('缺少授权码');
        }
        
        // 获取微信用户信息
        $wxInfo = $this->getWxUserInfo($input['code']);
        
        if (isset($wxInfo['errcode'])) {
            $this->error('微信登录失败: ' . $wxInfo['errmsg']);
        }
        
        $openid = $wxInfo['openid'];
        $sessionKey = $wxInfo['session_key'];
        
        try {
            // 检查用户是否已存在
            $sql = "SELECT * FROM users WHERE openid = ?";
            $user = $this->db->fetchOne($sql, [$openid]);
            
            if (!$user) {
                // 创建新用户
                $token = $this->generateToken($openid);
                $sql = "INSERT INTO users (openid, session_key, token, token_expires, created_at) 
                        VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 7 DAY), NOW())";
                
                $this->db->execute($sql, [$openid, $sessionKey, $token]);
                $userId = $this->db->lastInsertId();
                
                $user = [
                    'id' => $userId,
                    'openid' => $openid,
                    'token' => $token,
                    'nickname' => '',
                    'avatar' => '',
                    'phone' => ''
                ];
            } else {
                // 更新现有用户
                $token = $this->generateToken($openid);
                $sql = "UPDATE users SET session_key = ?, token = ?, 
                        token_expires = DATE_ADD(NOW(), INTERVAL 7 DAY), 
                        updated_at = NOW() WHERE id = ?";
                
                $this->db->execute($sql, [$sessionKey, $token, $user['id']]);
                $user['token'] = $token;
            }
            
            // 记录登录日志
            $this->logApi('login', ['user_id' => $user['id']]);
            
            $this->success([
                'token' => $user['token'],
                'userInfo' => [
                    'id' => $user['id'],
                    'nickname' => $user['nickname'] ?? '',
                    'avatar' => $user['avatar'] ?? '',
                    'phone' => $user['phone'] ?? ''
                ]
            ], '登录成功');
            
        } catch (Exception $e) {
            $this->error('登录失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取用户信息
     */
    public function profile() {
        $user = $this->getCurrentUser();
        
        $this->success([
            'id' => $user['id'],
            'nickname' => $user['nickname'] ?? '',
            'avatar' => $user['avatar'] ?? '',
            'phone' => $user['phone'] ?? '',
            'created_at' => $this->formatTime($user['created_at'])
        ]);
    }
    
    /**
     * 更新用户信息
     */
    public function updateProfile() {
        $user = $this->getCurrentUser();
        $input = json_decode(file_get_contents('php://input'), true);
        
        $allowedFields = ['nickname', 'avatar', 'phone'];
        $updateData = [];
        $params = [];
        
        foreach ($allowedFields as $field) {
            if (isset($input[$field])) {
                $updateData[] = "$field = ?";
                $params[] = $input[$field];
            }
        }
        
        if (empty($updateData)) {
            $this->error('没有需要更新的数据');
        }
        
        try {
            $params[] = $user['id'];
            $sql = "UPDATE users SET " . implode(', ', $updateData) . 
                   ", updated_at = NOW() WHERE id = ?";
            
            $this->db->execute($sql, $params);
            
            $this->logApi('update_profile', ['user_id' => $user['id']]);
            $this->success(null, '更新成功');
            
        } catch (Exception $e) {
            $this->error('更新失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 刷新token
     */
    public function refreshToken() {
        $user = $this->getCurrentUser();
        
        try {
            $newToken = $this->generateToken($user['openid']);
            $sql = "UPDATE users SET token = ?, token_expires = DATE_ADD(NOW(), INTERVAL 7 DAY) 
                    WHERE id = ?";
            
            $this->db->execute($sql, [$newToken, $user['id']]);
            
            $this->success(['token' => $newToken], 'Token刷新成功');
            
        } catch (Exception $e) {
            $this->error('Token刷新失败: ' . $e->getMessage());
        }
    }
}

// 处理请求
$auth = new AuthAPI();

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

switch ($method) {
    case 'POST':
        switch ($action) {
            case 'login':
                $auth->login();
                break;
            case 'refresh':
                $auth->refreshToken();
                break;
            case 'refresh-token':
                // 兼容别名：与 refresh 等效
                $auth->refreshToken();
                break;
            default:
                $auth->error('无效的操作');
        }
        break;
        
    case 'GET':
        switch ($action) {
            case 'profile':
                $auth->profile();
                break;
            default:
                $auth->error('无效的操作');
        }
        break;
        
    case 'PUT':
        switch ($action) {
            case 'profile':
                $auth->updateProfile();
                break;
            default:
                $auth->error('无效的操作');
        }
        break;
        
    default:
        $auth->error('不支持的请求方法');
}
?>